package com.lagou.edu.dao;

import com.lagou.edu.pojo.Account;
import com.lagou.edu.utils.DruidUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author HZF
 * @date 2020/5/31 9:05
 * @description
 */
public class UserDao {


    private static final String name = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/bank";
    private static final String username = "root";
    private static final String password = "root";
    private static Connection connection = null;
    private static PreparedStatement preparedStatement = null;
    private void  JdbcTest(String sql){
        try{
            Class.forName(name);
            DriverManager.getConnection(url,username,password);
            connection.prepareStatement(sql);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void save(){
        System.out.println("UserDao save方法！！");
    }

    public Account queryAccountByCardNo(String cardNo) throws Exception {
        //从连接池获取连接

        Class.forName(name);
        Connection connection = DriverManager.getConnection(url, username, password);

        // Connection con = DruidUtils.getInstance().getConnection();
        String sql = "select * from account where cardNo=?";
        PreparedStatement preparedStatement = UserDao.connection.prepareStatement(sql);
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while(resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();
        //con.close();

        return account;
    }
    public int updateAccountByCardNo(Account account) throws Exception {

        Class.forName(name);
        DriverManager.getConnection(url,username,password);
        Connection con = DruidUtils.getInstance().getConnection();
        //Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where cardNo=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
        //con.close();
        return i;
    }
}
